package com.yx.study.leet.primary.design;

import java.util.Random;

/**
 * 设计问题-打乱数组
 * https://leetcode.cn/leetbook/read/top-interview-questions-easy/xn6gq1/
 */
public class Solution {
    private int[] nums;
    private Random random;

    public Solution(int[] nums) {
        this.nums = nums;
        random = new Random();
    }

    //重置数组，就是返回之前的数组
    public int[] reset() {
        return nums;
    }


    //打乱数组
    public int[] shuffle() {
        if (nums == null)
            return null;
        int[] a = nums.clone();//clone一个新的数组
        for (int j = 1; j < a.length; j++) {
            int i = random.nextInt(j + 1);
            swap(a, i, j);
        }
        return a;
    }

    //交换两个数字的值 位运算实现数值交换
    private void swap(int[] a, int i, int j) {
        if (i != j) {
            a[i] ^= a[j];
            a[j] ^= a[i];
            a[i] ^= a[j];
        }
    }

}
